/**
 * 📊 统计工具类
 * 提供各种统计计算功能
 */

/**
 * 计算基础统计量
 * @param {number[]} numbers - 数字数组
 * @returns {object} 统计结果
 */
function calculateStats(numbers) {
  if (!numbers || numbers.length === 0) {
    return { mean: 0, median: 0, stdDev: 0, min: 0, max: 0, variance: 0 };
  }

  // 均值
  const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;

  // 中位数
  const sorted = [...numbers].sort((a, b) => a - b);
  const median = numbers.length % 2 === 0
    ? (sorted[numbers.length / 2 - 1] + sorted[numbers.length / 2]) / 2
    : sorted[Math.floor(numbers.length / 2)];

  // 方差和标准差
  const variance = numbers.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / numbers.length;
  const stdDev = Math.sqrt(variance);

  // 最小值和最大值
  const min = Math.min(...numbers);
  const max = Math.max(...numbers);

  return { mean, median, stdDev, min, max, variance };
}

/**
 * 线性回归
 * @param {number[]} xValues - X轴数值
 * @param {number[]} yValues - Y轴数值
 * @returns {object} 斜率和截距
 */
function linearRegression(xValues, yValues) {
  if (!xValues || !yValues || xValues.length === 0 || xValues.length !== yValues.length) {
    return { slope: 0, intercept: 0 };
  }

  const n = xValues.length;
  const sumX = xValues.reduce((a, b) => a + b, 0);
  const sumY = yValues.reduce((a, b) => a + b, 0);
  const sumXY = xValues.reduce((sum, x, i) => sum + x * yValues[i], 0);
  const sumX2 = xValues.reduce((sum, x) => sum + x * x, 0);

  const denominator = n * sumX2 - sumX * sumX;
  
  if (denominator === 0) {
    return { slope: 0, intercept: sumY / n };
  }

  const slope = (n * sumXY - sumX * sumY) / denominator;
  const intercept = (sumY - slope * sumX) / n;

  return { slope, intercept };
}

/**
 * 预测未来值
 * @param {number[]} historicalData - 历史数据
 * @param {number} periodsAhead - 预测未来几期
 * @returns {number[]} 预测结果
 */
function predictFuture(historicalData, periodsAhead) {
  if (!historicalData || historicalData.length < 2) {
    return Array(periodsAhead).fill(0);
  }

  const xValues = historicalData.map((_, i) => i);
  const yValues = historicalData;

  const { slope, intercept } = linearRegression(xValues, yValues);

  const predictions = [];
  for (let i = 1; i <= periodsAhead; i++) {
    const x = historicalData.length + i - 1;
    const predicted = slope * x + intercept;
    predictions.push(Math.max(0, predicted)); // 不能为负
  }

  return predictions;
}

/**
 * 计算变异系数 (Coefficient of Variation)
 * @param {number[]} numbers - 数字数组
 * @returns {number} 变异系数(%)
 */
function calculateCV(numbers) {
  const stats = calculateStats(numbers);
  if (stats.mean === 0) return 0;
  return (stats.stdDev / stats.mean) * 100;
}

/**
 * 计算Z-Score（标准分数）
 * @param {number} value - 待检测的值
 * @param {number} mean - 均值
 * @param {number} stdDev - 标准差
 * @returns {number} Z分数
 */
function calculateZScore(value, mean, stdDev) {
  if (stdDev === 0) return 0;
  return (value - mean) / stdDev;
}

/**
 * 计算百分位数
 * @param {number[]} numbers - 数字数组
 * @param {number} percentile - 百分位（0-100）
 * @returns {number} 百分位数值
 */
function calculatePercentile(numbers, percentile) {
  if (!numbers || numbers.length === 0) return 0;
  
  const sorted = [...numbers].sort((a, b) => a - b);
  const index = (percentile / 100) * (sorted.length - 1);
  const lower = Math.floor(index);
  const upper = Math.ceil(index);
  const weight = index - lower;
  
  return sorted[lower] * (1 - weight) + sorted[upper] * weight;
}

module.exports = {
  calculateStats,
  linearRegression,
  predictFuture,
  calculateCV,
  calculateZScore,
  calculatePercentile
};

